package com.nerve.cloudoffice.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.nerve.cloudoffice.domain.Task;
import com.nerve.cloudoffice.domain.User;

/**
 * @project: cloudOffice
 * @file: JSONHelper.java
 * @package: com.nerve.cloudoffice.common.util
 * @description:
 *	针对FastJson的支持类
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: 2013-8-4
 * @change log:
 */
public class JSONHelper {

	public static ValueFilter getValueFilter(Class<?> clz){
		/*
		 * Task 类别时，对于sender，worker这些User引用，只返回相应的name就可以了
		 */
		if(clz.getName().endsWith("Task")){
			return new ValueFilter() {
				public Object process(Object arg0, String arg1, Object arg2) {
					if(arg1.equals("sendUser") || arg1.equals("workUser")){
						return arg2 == null?arg2:((User)arg2).getName();
					}
					
					return arg2;
				}
			};
		}
		else if(clz.getName().endsWith("Notify")){
			return new ValueFilter() {
				public Object process(Object arg0, String arg1, Object arg2) {
					if(arg1.equals("user")){
						return arg2 == null?arg2:((User)arg2).getName();
					}
					
					return arg2;
				}
			};
		}
		else if(clz.getName().endsWith("TrashApply")){
			return new ValueFilter() {
				public Object process(Object arg0, String arg1, Object arg2) {
					if(arg1.equals("sender") || arg1.equals("passer")){
						return arg2 == null?arg2:((User)arg2).getName();
					}
					else if(arg1.equals("task")){
						return arg2 == null?arg2:((Task)arg2).getTitle();
					}
					
					return arg2;
				}
			};
		}
		
		return null;
	}
	
	
	/**
	 * @method name: toJSON
	 * @description: 
	 * @return type: String
	 *	@param obj
	 *	@return
	 */
	public static String toJSON(Object obj){
		String json = JSON.toJSONString(
				obj, 
				SerializerFeature.DisableCircularReferenceDetect,
				SerializerFeature.WriteMapNullValue
				);
		
		return json;
	}
}